<template>
  <div class="am-u-sm-12 am-u-md-12 am-u-lg-12 discount-code-form">
    <div class="widget am-cf">
      <div class="widget-head am-cf">
        <div class="widget-title am-fl">生成优惠码</div>
        <div class="widget-function am-fr">
          <button type="button" class="am-btn am-btn-default" @click="$router.go(-1)">返回</button>
        </div>
      </div>
      <div class="widget-body am-fr">
        <form class="am-form tpl-form-border-form tpl-form-border-br" data-am-validator :id="id">
          <fieldset>
            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>优惠券名称
              </label>
              <div class="am-u-sm-9 input-field">
                <input type="text" class="am-form-field" placeholder="优惠券名称" required v-model="formData.name">
              </div>
            </div>
            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>优惠类型
              </label>
              <div class="am-u-sm-9 input-field">
                <el-select size="small" 
                  v-model="formData.discountType" placeholder="请选择优惠类型">
                  <el-option
                    v-for="item in types"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>
            <div class="am-form-group" v-if="formData.discountType==1">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>折扣
              </label>
              <div class="am-u-sm-9 input-field">
                <input type="number" class="am-form-field" placeholder="填写内容如：0.98" required v-model="formData.discountAmount" min="0" max="1" @blur="regNumber()">
              </div>
            </div>
            <div class="am-form-group" v-if="formData.discountType==0">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>扣减额度（元）
              </label>
              <div class="am-u-sm-9 input-field">
                <input type="text" class="am-form-field" placeholder="扣减额度" required v-model="formData.discountAmount" >
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>最低消费（元）
              </label>
              <div class="am-u-sm-9 input-field">
                <input type="text" class="am-form-field" placeholder="最低消费" required v-model="formData.orderThresholdAmount">
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>生成数量（张）
              </label>
              <div class="am-u-sm-9 input-field">
                <input type="text" class="am-form-field" placeholder="生成数量" max="10000" required v-model="formData.amount">
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>生效开始时间
              </label>
              <div class="am-u-sm-3 am-u-end input-field">
                <date-time-picker
                  v-model="formData.effectiveStartTimestamp"
                  format="YYYY-MM-DD HH:mm:ss">
                  <input data-am-datetimepicker class="am-form-field" placeholder="开课时间">
                </date-time-picker>
              </div>
            </div>


            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>生效结束时间
              </label>
              <div class="am-u-sm-3 am-u-end input-field">
                <date-time-picker
                  v-model="formData.effectiveEndTimestamp"
                  format="YYYY-MM-DD HH:mm:ss">
                  <input data-am-datetimepicker class="am-form-field" placeholder="开课时间">
                </date-time-picker>
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                <span class="am-text-danger am-margin-right-xs am-text-xs">*</span>所属区域
              </label>
              <div class="am-u-sm-3 am-u-end input-field">
                <select2 required v-model="formData.areaTeamId" :options="areaTeams">
                  <option value="">请选择</option>
                </select2>

              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                适用业务组
              </label>
              <div class="am-u-sm-9  input-field">
                <el-select @change="handleChange(arguments[0], 'busTeamIds', busTeams)" v-model="formData.busTeamIds" multiple placeholder="选择业务组">
                  <el-option label="全部" value="-1">
                  </el-option>
                  <el-option
                    v-for="item in busTeams"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                适用产品
              </label>
              <div class="am-u-sm-9  input-field">
                <el-select @change="handleChange(arguments[0], 'productIds', productList,'productId')" v-model="formData.productIds" multiple placeholder="选择业务组">
                  <el-option label="全部" value="-1">
                  </el-option>
                  <el-option
                    v-for="item in productList"
                    :key="item.productId"
                    :label="item.name"
                    :value="item.productId">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                适用课程
              </label>
              <div class="am-u-sm-9  input-field">
                <el-select @change="handleChange(arguments[0], 'courseTemplateIds', templateCourseList,'courseTemplateId')"
                           v-model="formData.courseTemplateIds" multiple placeholder="选择课程">
                  <el-option label="全部" value="-1">
                  </el-option>
                  <el-option
                    v-for="item in templateCourseList"
                    :key="item.courseTemplateId"
                    :label="item.courseName"
                    :value="item.courseTemplateId">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                适用期数
              </label>
              <div class="am-u-sm-9 input-field">
                <el-select @change="handleChange(arguments[0], 'periodIds', periods,'periodId')"
                           v-model="formData.periodIds" multiple placeholder="选择期数">
                  <el-option label="全部" value="-1">
                  </el-option>
                  <el-option
                    v-for="item in periods"
                    :key="item.periodId"
                    :label="item.periodName"
                    :value="item.periodId">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                适用年级
              </label>
              <div class="am-u-sm-9  input-field">
                <el-select @change="handleChange(arguments[0], 'gradeIds', grades,'gradeId')"
                           v-model="formData.gradeIds" multiple placeholder="选择年级">
                  <el-option label="全部" value="-1">
                  </el-option>
                  <el-option
                    v-for="item in grades"
                    :key="item.gradeId"
                    :label="item.gradeName"
                    :value="item.gradeId">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="am-form-group">
              <label class="am-u-sm-3 am-form-label">
                适用科目
              </label>
              <div class="am-u-sm-9 input-field">
                <el-select @change="handleChange(arguments[0], 'subjectIds', subjects,'subjectId')"
                           v-model="formData.subjectIds" multiple placeholder="选择科目">
                  <el-option label="全部" value="-1">
                  </el-option>
                  <el-option
                    v-for="item in subjects"
                    :key="item.subjectId"
                    :label="item.subjectName"
                    :value="item.subjectId">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="am-form-group">
              <div class="am-u-sm-9 am-u-sm-push-3">

                <button type="submit" class="am-btn am-btn-primary">提交</button>
              </div>
            </div>
          </fieldset>
        </form>
      </div>
    </div>
  </div>
</template>
<script>
  import io from '../../lib/io'
  import util from '../../lib/util'
  import conf from '../../lib/conf'
  import math from '../../lib/math'
  import moment from 'moment'
  import SelectDiscount from './SelectDiscount'


  export default{
    components:{'select-discount':SelectDiscount},
    data(){
      return {
        productList:[],
        templateCourseList:[],
        periods:[],
        types:[
          {
           label:'额度优惠',
           value:'0'
          },
          {
           label:'折扣优惠',
           value:'1'
          },
        ],
        formData: {
          areaTeamId:'',
          busTeamIds:[],
          periodIds:[],
          productIds:[],
          courseTemplateIds:[],
          gradeIds:[],
          subjectIds:[],
          name: '',
          discountAmount: '',
          orderThresholdAmount: '',
          amount: '',
          effectiveStartTimestamp: '',
          effectiveEndTimestamp: '',
          discountType:'0',
          // discountRate:"",
        }
      }
    },
    created: function () {
      this.formData.areaTeamId = window.config.areaTeams[0].areaTeamId
    },
    watch: {
      'formData.areaTeamId':function(val, oVal){
        if (oVal){
          this.formData.productIds = []
          this.formData.courseTemplateIds = []
          this.formData.busTeamIds = []
          this.formData.periodIds=[]
        }
        this.loadProductData()
        this.loadTemplateCourseData()
        this.loadPeriodData()

      }
    },
    computed: {
      grades: function () {
        return this.$root.config.grades || []
      },
      subjects: function () {
        return this.$root.config.subjects || []
      },
      areaTeams: function () {
        var options = ( this.$root.config.areaTeams || [] )
          .map(function (item) {
            return {value: item.areaTeamId, text: item.name}
          })
        return options
      },
      busTeams: function () {
        var options = ( ( this.formData.areaTeamId  ) ? ( this.$root.config.groupBusTeams[this.formData.areaTeamId] || [] ) : [] )
          .map(function (item) {
            return {value: item.busTeamId, text: item.name}
          })

        return options
      },

    },
    mounted: function () {
      var _this = this;
      $('#' + this.id).validator({
        onValid: function (validity) {
          $(validity.field).closest('.input-field').find('.am-alert').hide();
        },
        onInValid: function (validity) {
          var $field = $(validity.field);
          var $group = $field.closest('.input-field');
          var $alert = $group.find('.am-alert');
          // 使用自定义的提示信息 或 插件内置的提示信息
          var msg = $field.data('validationMessage') || this.getValidationMessage(validity);

          if (!$alert.length) {
            $alert = $('<div class="am-alert am-alert-danger"></div>').hide().appendTo($group);
          }

          $alert.html(msg).show();
        },
        submit: function (e) {
          e.preventDefault();
          var $submitBtn = $('button[type=submit]', e.target);
          $submitBtn.attr("disabled", "disabled")
          _this.$showLoading()
          var formValidity = this.isFormValid();
          var complete = function () {
            _this.$hiddenLoading()
            _this.$root.$emit('reloadConfig')
            $submitBtn.removeAttr("disabled", "disabled")
          }
          if (formValidity) {
            _this.save(complete);
          } else {
            complete.call()
          }
        }
      });
    },
    methods: {
      regNumber(){
      let number = this.formData.discountAmount
      var toFixedNum = Number(number).toFixed(3);     
      var realVal = toFixedNum.substring(0, toFixedNum.toString().length - 1);//不要四舍五入
      this.formData.discountAmount = realVal
      },
      handleChange (val, param, list, alia) {
        alia = alia || 'value'
        if (val.length > 0 && val[val.length - 1] === '-1') {
          this.formData[param] = []
          list.map(i => {
            this.formData[param].push(i[alia])
          })
        }
      },
      save: function (complete) {

        var data = Object.assign({}, this.formData)

        if (!data.effectiveStartTimestamp) {
          this.$alert('请选择生效开始时间')
          complete.call()
          return
        }
        if (!data.effectiveEndTimestamp) {
          this.$alert('请选择生效结束时间')
          complete.call()
          return
        }
        data.effectiveStartTimestamp = new Date(data.effectiveStartTimestamp).getTime()
        data.effectiveEndTimestamp = new Date(data.effectiveEndTimestamp).getTime()
        data.productIds = data.productIds ? data.productIds.join(','):''
        data.courseTemplateIds = data.courseTemplateIds?data.courseTemplateIds.join(','):''
        data.gradeIds = data.gradeIds ? data.gradeIds.join(',') :''
        data.subjectIds = data.subjectIds ? data.subjectIds.join(','):''
        data.busTeamIds = data.busTeamIds ? data.busTeamIds.join(','):''
        data.periodIds = data.periodIds ? data.periodIds.join(','):''

        // if(data.discountType==0){
        //   delete data.discountAmount
        // }else if(data.discountType==1){
        //   delete data.discountRate
        // }
          
        var _this = this
        // let param = {
        //   discountCodeCreateVo:JSON.stringify(data)
        // }
        io.post(io.createDiscountCode,data,
          function (ret) {
            complete.call()
            if (ret.success) {
              _this.$toast('OK')
              _this.$router.push('/main/discount/discountcode/list')
            } else {
              _this.$alert(ret.desc)
            }
          },
          function () {
            complete.call()
            _this.$alert('请求服务器失败')
          })
      },
      loadProductData: function () {
        var _this = this
        io.post(io.apiAdminBaseProductListForAreaTeam, {
          areaTeamId : _this.formData.areaTeamId
        }, function (ret) {
          if (ret.success) {
            _this.productList = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
      loadTemplateCourseData: function () {
        var _this = this
        io.post(io.apiAdminBaseCourseTemplateListForAreaTeam, {
          areaTeamId : _this.formData.areaTeamId
        }, function (ret) {
          if (ret.success) {
            _this.templateCourseList = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
      loadPeriodData: function () {
        var _this = this
        io.post(io.apiAdminPeriodListForAreaTeam, {
          areaTeamId : this.formData.areaTeamId
        }, function (ret) {
          if (ret.success) {
            _this.periods = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
    }
  }

</script>

<style>
  .discount-code-form .el-tag+.el-tag {
    margin-left: 10px;
    margin-top: 5px;
  }
  .discount-code-form .el-select {
    width: 100%;
  }
  .discount-code-form .am-form input[type=text][readonly] {
    background-color: #fff;
    cursor: text;
  }
</style>
